<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>查看上传的文件</title>
  <link rel="stylesheet" href="../css/uikit.min.css">
  <!-- <link rel="stylesheet" href="../css/tailwind.min.css"> -->

  <script src="../javaScript/uikit.min.js"></script>
  <script src="../javaScript/uikit-icons.min.js"></script>

  <style>
    .listItem {
      display: flex;
      justify-content: space-between;
      align-items: center;
      width: 100%;
    }

    .listItemTitle {
      cursor: pointer;
      width: auto;
      max-width: 78%;
      word-break: break-all;
    }

    .listItemA {
      white-space: nowrap;
      margin-left: 10px;
      display: block;
      max-width: 100%;
    }

    .content_ {
      width: 100%;
      display: flex;
      box-sizing: border-box;
    }

    .update_ {
      width: 50%;
      padding: 0 15px;
    }

    .titleDec {
      background: #d8d8d8;
      border-radius: 4px;
      line-height: 40px;
      padding: 10px;
    }

    @media screen and (max-width: 992px) {
      .update_ {
        width: 100%;
        box-sizing: border-box;
      }

      .content_ {
        display: block;
        box-sizing: border-box;
      }
    }
  </style>
</head>

<body style="background-color: #e7e7e7; min-height: 100vh;">
  <div style="text-align: center;background-color: #f5b128; font-size: 20px; padding: 15px; margin-bottom: 20px;">
    <div style="margin-bottom: 10px;">默认展示的是 _myDefault 用户的所有缓存文件！</div>
    <div>如果想查看其他用户的缓存文件，可以在下面的搜索框中输入用户名再查询！</div>
  </div>

  <div class="content_">
    <div class="update_" style="margin-bottom: 20px;">
      <div style="width: 100%; ">
        <div class="uk-margin">
          <div class="uk-inline" style="width:100% ;">
            <a class=" uk-form-icon" tabindex="-1" href="#" uk-icon="icon: pencil"></a>
            <input name="search" id="search" class="uk-input uk-form-width-large uk-form-large" type="text"
              style="width: 100%;" placeholder="输入用户名，查看所有文件">
          </div>
        </div>
        <button onclick="searchFn()" class="uk-button uk-button-primary uk-button-medium uk-margin-small-bottom"
          type="button" tabindex="-1"
          style="width: 100%; margin-bottom: 20px !important; height: 60px; font-size: 20px; word-break: keep-all; background-color: #336699;">查询用户名</button>
      </div>

      <hr style="border-bottom: 4px solid #dfd3d3;">

      <div style="width: 100%;">
        <div class="uk-margin">
          <div class="uk-inline" style="width:100% ;">
            <a class=" uk-form-icon" tabindex="-1" href="#" uk-icon="icon: pencil"></a>
            <input name="username" class="uk-input uk-form-width-large uk-form-large" type="text" style="width: 100%;"
              placeholder="输入用户名。必须填">
          </div>
        </div>
        <div class="uk-margin">
          <div class="uk-inline" style="width:100% ;">
            <a class=" uk-form-icon" tabindex="-1" href="#" uk-icon="icon: pencil"></a>
            <input name="message" class="uk-input uk-form-width-large uk-form-large" type="text" style="width: 100%;"
              placeholder="用途说明。可不填">
          </div>
        </div>
        <button class="uk-button uk-button-danger uk-button-medium uk-margin-small-bottom" type="button" tabindex="-1"
          style="width: 100%; margin-bottom: 20px !important; height: 60px; font-size: 20px; word-break: keep-all; background-color: #188888;"
          onclick="createUsername()">创建用户</button>
      </div>

      <div id="createHttp" hidden class="uk-section" style="background-color: #cecece;">
        <div class="uk-container uk-container-small" style="font-size: 20px;">
          <p>创建成功，快用下面的链接分享给你的朋友，让他们上传文件吧！</p>
          <em style="font-size: 20px; word-break: break-all;"
            id="shareHttp">http://localhost:8422/pages/showFiles.html</em>
          <button class="uk-button uk-button-danger uk-button-medium uk-margin-small-bottom" type="button" tabindex="-1"
            style="width: 100%; margin-bottom: -10px !important; margin-top: 30px; height: 60px; font-size: 20px; word-break: keep-all; background-color: #188888;"
            onclick="(()=>{
              copyText(document.getElementById('shareHttp').innerHTML.trim());
              UIkit.notification({ message: '复制成功', status: 'success', pos: 'top-right',timeout: 1500 });
              })()">复制链接</button>
          <button class="uk-button uk-button-danger uk-button-medium uk-margin-small-bottom" type="button" tabindex="-1"
            style="width: 100%; margin-bottom: -10px !important; margin-top: 30px; height: 60px; font-size: 20px; word-break: keep-all; background-color: #188888;"
            onclick="(()=>{
              window.open(document.getElementById('shareHttp').innerHTML.trim());
              })()">打开链接</button>
        </div>
      </div>

    </div>

    <!-- <hr style="border-bottom: 4px solid #dfd3d3;"> -->

    <div class="update_" style="padding: 0 15px 200px 15px;">
      <h4 id="usernameshow" class="titleDec">用户的所有文件如下</h4>
      <ul class="uk-list uk-list-striped" id="listFiles" style="font-size: 18px;">
        <!-- <li>上传成功的文件如下</li> -->
      </ul>
    </div>
  </div>

  <script>
    function searchFn() {
      let search = document.getElementById("search").value;
      // if (!search.trim()) return;
      overHash({ "search": search.trim() })
      getFileNames(search.trim() || '_myDefault')
    }
    // 监听键盘
    document.addEventListener('keydown', (ev) => {
      if (ev.keyCode == 13) {
        if (document.activeElement.name == 'search')
          searchFn()
      }
    });

    // 查询用户名对应的所有文件
    function getFileNames(username, isShowTip = true) {
      isShowTip && UIkit.notification({ message: `正在查询《${username}》用户的文件，请稍后`, status: 'success', pos: 'top-right', timeout: 1500 })
      document.getElementById('usernameshow').innerHTML = "《" + username + '》用户的所有文件如下'
      document.getElementById("listFiles").innerHTML = ''
      fetch(`/showFiles?username=${encodeURIComponent(username)}`, {}).then(response => {
        if (response.status >= 200 && response.status < 300) { // 判断请求是否成功
          return response.json() // 得到文本字符串。
        } else {
          throw new Error(response.statusText);
        }
      }).then(json => {
        if (json.success) {
          let downloadHref = location.origin + '/updateFiles/' + encodeURIComponent(username);

          json.filesList.forEach(element => {
            element = encodeURIComponent(element)
            var oLi = document.createElement("li");
            oLi.innerHTML = `
              <div class="listItem">
                
                <div class="listItemTitle" title="点击查看文件" target="_blank"  
                onclick="window.open('${downloadHref + '/' + element}')" >${decodeURIComponent(element)}</div>

                <div class="listItemA" >
                  <a title="点击下载文件" href="${downloadHref + '/' + element}" download class="uk-icon-link" uk-icon="icon: cloud-download; ratio: 1.5"></a>
                  
                  <a title="复制文件链接" href="javascript:" onclick="(
                    ()=>{
                      copyText('${downloadHref + '/' + element}');
                      UIkit.notification({ message: '成功复制文件链接', status: 'success', pos: 'top-right',timeout: 1500 })
                    }
                  )()" class="" uk-icon="icon: copy; ratio: 1.5"></a>
                  </div>
              </div>`
            document.getElementById("listFiles").appendChild(oLi)
          });
        }
        // else alert(json.message)
        isShowTip && UIkit.notification({ message: json.message, status: 'success', pos: 'top-right', timeout: 1500 })
      }).catch(err => {
        console.log('Request Failed', err)
      })
    }
    (() => {
      let o = overHash();
      getFileNames(o.search || '_myDefault', false)
      o.search && (document.getElementById("search").value = o.search)
      o.username && (document.getElementsByName("username")[0].value = o.username)
      o.message && (document.getElementsByName("message")[0].value = o.message)
    })()


    // 创建一个私有的用户链接
    function createUsername() {
      let username = document.getElementsByName("username")[0].value
      let message = document.getElementsByName("message")[0].value
      overHash({ username, message })
      fetch(`/encodeUsername?username=${encodeURI(username)}&message=${encodeURI(message)}`, {}).then(response => {
        if (response.status >= 200 && response.status < 300) { // 判断请求是否成功
          return response.text() // 得到文本字符串。
        } else {
          throw new Error(response.statusText);
        }
      }).then(json => {
        // console.log(json);  // 得到最终结果。
        let data = JSON.parse(json)
        document.getElementById('createHttp').hidden = false
        document.getElementById('shareHttp').innerHTML = location.origin + `/pages/updateFiles.html?message=${encodeURI(data.message)}#${data.username}`;
        UIkit.notification({ message: '成功创建用户，可以分享给朋友上传文件', status: 'success', pos: 'top-right', timeout: 1500 })
      }).catch(err => {
        console.log('Request Failed', err)
      });
    }


    // 下载文件
    function downloadFiles(href) {
      var downloadElement = document.createElement("a");
      downloadElement.href = href;
      // downloadElement.download = `scorecard ${date}.csv`; // 下载后文件名
      document.body.appendChild(downloadElement);
      downloadElement.click(); // 点击下载
      document.body.removeChild(downloadElement); // 下载完成移除元素
    }


    // 复制文本内容
    function copyText(text) {
      console.log('', text)
      let inputDom = document.createElement('input');  // 创建一个input元素
      inputDom.setAttribute('readonly', 'readonly'); // 防止手机上弹出软键盘
      inputDom.value = text; // 给input元素赋值
      document.body.appendChild(inputDom); // 添加到body
      inputDom.select(); //选中input元素的内容
      document.execCommand('Copy'); // 执行浏览器复制命令
      inputDom.style.display = 'none';
      inputDom.remove(); // 移除input元素
    }

    // 操作location.hash
    function overHash(obj) {
      let preObj = {};
      try {
        let hash = location.hash.trim().substr(1)
        preObj = JSON.parse(decodeURIComponent(hash))
      } catch (error) {
        preObj = {}
      }
      if (obj) {
        preObj = Object.assign(preObj, obj)
        location.hash = encodeURIComponent(JSON.stringify(preObj))
      };
      return preObj
    }

  </script>

</body>

</html>